﻿using Exceptionless;
using Exceptionless.Plugins.Default;
using Microsoft.Extensions.Logging;
using NLog;
using ZilLion.Service.Core.ConfigManager.Manager;

namespace ZilLion.Service.Core.Log
{
    public partial class DefaultLogger
    {
        #region ExceptionlessClient

        /// <summary>
        ///     错误Client
        /// </summary>
        protected virtual ExceptionlessClient ErrorClient { get; set; }

        /// <summary>
        ///     MessageClient
        /// </summary>
        protected virtual ExceptionlessClient MessageClient { get; set; }

        /// <summary>
        ///     NloggerClient
        /// </summary>
        protected Logger NLoggerClient;

        /// <summary>
        ///     初始化ExceptionlessClient
        /// </summary>
        public void InitExceptionlessClient()
        {
            NLoggerClient = LogManager.GetCurrentClassLogger();
            var exceptionUrlApiKey = ZilLionConfigurationManager.GetConfigInstance<LoggerConfig>().ExceptionUrlApiKey;
            var serverUrl = ZilLionConfigurationManager.GetConfigInstance<LoggerConfig>().ExceptionUrl;
            ErrorClient = new ExceptionlessClient(c =>
            {
                c.ApiKey = exceptionUrlApiKey;
                c.ServerUrl = serverUrl;
            });


            MessageClient = new ExceptionlessClient(c =>
            {
                c.ApiKey = exceptionUrlApiKey;
                c.ServerUrl = serverUrl;
            });

            #region Init SubmittedEvent

            ErrorClient.SubmittedEvent += (s, e) =>
            {
                var ex = e?.PluginContextData?.GetException();
                if (ex != null)
                    NLoggerClient?.Error(ex);
            };

            #endregion

            #region     UseInMemoryStorage

            ErrorClient.Configuration.UseInMemoryStorage();
            MessageClient.Configuration.UseInMemoryStorage();
            ErrorClient.Configuration.AddPlugin<HandleAggregateExceptionsPlugin>();

            #endregion
        }

        #endregion
    }
}